package com.student.Activitys.activity;

import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.facebook.drawee.view.SimpleDraweeView;
import com.student.Activitys.R;
import com.student.Activitys.activity.base.BaseActivity;
import com.student.Activitys.adapter.HomeGridAdapter;
import com.student.Activitys.adapter.HomeSurveyAdapter;
import com.student.Activitys.adapter.ImageTextAdapter;
import com.student.Activitys.adapter.base.BaseRecyleViewAdapter;
import com.student.Activitys.adapter.base.BaseRefreshAdapter;
import com.student.Activitys.bean.CarouselBean;
import com.student.Activitys.bean.CollegeSurveyBean;
import com.student.Activitys.bean.HomeGridBean;
import com.student.Activitys.bean.HomeNoticeBean;
import com.student.Activitys.bean.ImageTextBean;
import com.student.Activitys.bean.InfoReturnBean;
import com.student.Activitys.bean.ScheduleWeekBean;
import com.student.Activitys.bean.pack.ImageTextJsonPack;
import com.student.Activitys.dialog.HomeSignDialog;
import com.student.Activitys.http.manager.HomeManager;
import com.student.Activitys.utils.Constant;
import com.student.Activitys.utils.DataUtils;
import com.student.Activitys.utils.JumperUtils;
import com.student.Activitys.utils.ToastUtils;
import com.student.Activitys.view.recyleview.FullyGridLayoutManager;
import com.student.Activitys.view.recyleview.FullyLinearLayoutManager;
import com.zhy.autolayout.AutoLinearLayout;

import org.simple.eventbus.Subscriber;
import org.simple.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import cn.bingoogolapple.bgabanner.BGABanner;

/**
 * 项目名称：智慧校园学生端
 * 类描述：首页
 * 创建人：张飞祥
 * 创建时间：2017/9/18 11:11
 * 修改人：张飞祥
 * 修改时间：2017/9/18 11:11
 * 修改备注：
 */
public class HomeActivity extends BaseActivity {

    @Bind(R.id.tv_home_notice)
    TextView tvHomeNotice;
    @Bind(R.id.rv_home_function_list)
    RecyclerView rvHomeFunctionList;
    @Bind(R.id.rv_home_dynamic_list)
    RecyclerView rvHomeDynamicList;
    @Bind(R.id.rv_home_survey_list)
    RecyclerView rvHomeSurveyList;
    @Bind(R.id.layout_home_notice)
    AutoLinearLayout layoutHomeNotice;
    @Bind(R.id.banner_home_icon)
    BGABanner bannerHomeIcon;
    @Bind(R.id.sv_home)
    ScrollView svHome;


    //初始化网络请求
    public HomeManager mApiManager;
    //功能栏按钮 适配器
    private HomeGridAdapter adapter;
    //学院概况 适配器
    private HomeSurveyAdapter surveyAdapter;
    //校内动态适配器
    private ImageTextAdapter dynamicAdapter;
    //校内动态 List集合
    private List<ImageTextBean> homeDynamicList = null;
    //上拉加载 是否滑动到底部 重复了加载
    private boolean dynamicFlag = true;
    //上拉加载 没有数据 page 是否 +1
    private boolean dynamicPageFlag = true;
    //签到 dialog
    private HomeSignDialog signMsgDialog = null;
    //签到提示 diaolog
    public MaterialDialog signDialog;
    /**
     * 分页加载  所需变量
     */
    private int page = 1;              //当前页
    private int rows = 5;              //数据行数

    //功能导航图标
    private int[] icons = {R.drawable.act_home_my, R.drawable.act_home_assess_icon,
            R.drawable.act_home_politics_icon, R.drawable.act_home_support_icon, R.drawable.act_home_schedule_icon,
            R.drawable.act_home_push, R.drawable.act_home_navigation_icon, R.drawable.act_home_sign_icon};

    //学院概况 暂时图片
    private int[] surveyImgs = {R.drawable.home_imag_01, R.drawable.home_imag_02};
    //学院概况 暂时文字
    private String[] surveyTitle = {"了解学院", "学在警院", "思政中心"};

    //功能导航文字
    private String[] strs = {"我的信息", "阶段评价", "思政中心", "奖惩资助", "我的课表", "历史推送", "校内导航", "签到"};
    //功能栏实体
    private HomeGridBean homeGrid = null;
    private List<HomeGridBean> homeGridList = null;


    @Override
    protected void initUI() {
        setContentView(R.layout.act_home);
        //网络请求 常驻方法
        mApiManager = mApiManager.getHomeApiManager(HomeActivity.this, HomeActivity.this.getTaskId());
        homeDynamicList = new ArrayList<>();
    }

    @Override
    protected void initData() {
        //初始化请求
        initHttp();
        //上拉加载事件
        initLoadMoreListener();
        //功能栏数据填充
        infarction();
        //解决滑动冲突
        rvHomeDynamicList.setNestedScrollingEnabled(false);
        svHome.smoothScrollTo(0, 0);

        /**
         * 学院概况 假数据
         */
        final List<CollegeSurveyBean> datas = new ArrayList<>();
        for (int i = 0; i < surveyImgs.length; i++) {
            CollegeSurveyBean bean = new CollegeSurveyBean();
            bean.setTitle(surveyTitle[i]);
            bean.setImage(surveyImgs[i]);
            datas.add(bean);
        }
        //填充列表数据
        surveyAdapter = new HomeSurveyAdapter(HomeActivity.this, datas);
        rvHomeSurveyList.setLayoutManager(new FullyLinearLayoutManager(HomeActivity.this, LinearLayoutManager.HORIZONTAL, false));
        rvHomeSurveyList.setAdapter(surveyAdapter);
        //学院概况点击事件
        surveyAdapter.setOnItemClickListener(new BaseRecyleViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putSerializable(Constant.COLLEGE_SURVEY_BEAN,datas.get(position));
                JumperUtils.JumpTo(HomeActivity.this,CollegeSurveyActivity.class,bundle);
            }
        });
    }


    @Override
    protected void getNotData() {

    }

    /**
     * 初始化默认请求
     */
    private void initHttp() {
        //设置首次加载 标记
        mApiManager.getType(Constant.FIRST_LOAD);
        //显示 加载dialog
        initShowTimeDialog("正在刷新页面数据，请稍后...",HomeActivity.this);
        //轮播图请求
        mApiManager.carouselList(Constant.HTTP_HOME_CAROUSEL_ACTION);
        //通知公告 （将来身份做为动态的）
        mApiManager.notice(Constant.HTTP_HOME_NOTICE_ACTION, Constant.IDENTITY_STUDENT);
        //校内动态
        mApiManager.homeDynamic(Constant.HTTP_HOME_DYNAMIC_ACTION, page + "", rows + "");
    }

    /**
     * 获取签到信息 http请求
     */
    private void initSignMsgHttp() {
        //显示 加载dialog
        initShowTimeDialog("正在加载当前签到数据，请稍后...",HomeActivity.this);
        //获取签到信息请求
        mApiManager.homeSignMsg(Constant.HTTP_HOME_SIGN_MSG_ACTION,xh);
    }

    /**
     * 签到 http请求
     */
    private void initSignHttp(ScheduleWeekBean bean) {
        //显示 加载dialog
        initShowTimeDialog("正在签到，请稍后...",HomeActivity.this);
        //获取签到信息请求
        mApiManager.homeSign(Constant.HTTP_HOME_SIGN_ACTION,xh,bean.getJSH(),
                bean.getKCH(),bean.getXNXQ(),bean.getSKZC(),bean.getSKXQ(),
                bean.getSKJC(),bean.getJXB());
    }

    /**
     * 功能栏
     */
    private void infarction() {
        /**
         * 数据填充
         */
        homeGridList = new ArrayList<>();
        for (int i = 0; i < icons.length; i++) {
            homeGrid = new HomeGridBean();
            homeGrid.setHomeIcon(icons[i]);
            homeGrid.setHomeStr(strs[i]);
            homeGridList.add(homeGrid);
        }
        //塞入列表 控件
        adapter = new HomeGridAdapter(HomeActivity.this, homeGridList);
        //设置 布局方式 （网格） 每行4列
        rvHomeFunctionList.setLayoutManager(new FullyGridLayoutManager(HomeActivity.this, 4));
        rvHomeFunctionList.setAdapter(adapter);
        adapter.setOnItemClickListener(new BaseRecyleViewAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                switch (position) {
                    case 0:    //我的信息
                        JumperUtils.JumpTo(HomeActivity.this, MyInfoActivity.class);
                        break;
                    case 1:     //阶段评价
                        JumperUtils.JumpTo(HomeActivity.this, StageSeeActivity.class);
                        break;
                    case 2:     //思政中心
                        JumperUtils.JumpTo(HomeActivity.this, PartyActivity.class);
                        break;
                    case 3:     //奖惩资助
                        JumperUtils.JumpTo(HomeActivity.this, SupportActivity.class);
                        break;
                    case 4:     //我的课表
                        JumperUtils.JumpTo(HomeActivity.this, ScheduleDayActivity.class);
                        break;
                    case 5:     //历史推送

                        break;
                    case 6:     //校内导航
                        JumperUtils.JumpTo(HomeActivity.this, SchoolMapActivity.class);
                        break;
                    case 7:     //签到
                        initSignMsgHttp();
                        break;
                }
            }
        });
    }

    /**
     * 校内动态点击事件
     */
    private void initDynamicItemClick() {
        if (dynamicAdapter != null) {
            dynamicAdapter.setOnItemClickListener(new BaseRefreshAdapter.OnRecyclerViewItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    /**
                     * 跳转 webView事件
                     */
                    Bundle bundle = new Bundle();
                    bundle.putString(Constant.WEB_METHOD, Constant.WEB_DYNAMIC_NOTICE);           //校内动态 方法名拼接字段
                    bundle.putString(Constant.WEB_ID, homeDynamicList.get(position).getId() + "");  //当前校内动态 id
                    bundle.putString(Constant.WEB_TITLE, "校内动态");                              //设置web页面标题
                    JumperUtils.JumpTo(HomeActivity.this, WebDateActivity.class, bundle);         //跳转到下一页面
                }
            });
        }
    }

    /**
     * 首页 轮播图 网络请求 返回具体 数据实体
     */
    @Subscriber(tag = Constant.BUS_HOME_CAROUSEL_LIST, mode = ThreadMode.MAIN)
    public void initDayList(final List<CarouselBean> list) {

        //设置 布局中 哪个控件加载某一个 图片
        bannerHomeIcon.setAdapter(new BGABanner.Adapter<SimpleDraweeView, String>() {
            @Override
            public void fillBannerItem(BGABanner banner, SimpleDraweeView itemView, String model, int position) {
                SimpleDraweeView simpleDraweeView = (SimpleDraweeView) itemView.findViewById(R.id.sdv_item_fresco_content);
                simpleDraweeView.setImageURI(Uri.parse(model));
            }
        });
        //抽离 image 路径
        List<String> urls = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            urls.add(list.get(i).getXXT_url());
        }
        //设置数据源
        bannerHomeIcon.setData(R.layout.item_home_carousel_fresco, urls, null);
        //设置轮播图响应事件
        bannerHomeIcon.setDelegate(new BGABanner.Delegate<SimpleDraweeView, String>() {
            @Override
            public void onBannerItemClick(BGABanner banner, SimpleDraweeView itemView, String model, int position) {
                /**
                 * 跳转 webView事件
                 */
                Bundle bundle = new Bundle();
                bundle.putString(Constant.WEB_METHOD, Constant.WEB_NAME_CAROUSEL);  //轮播图 方法名拼接字段
                bundle.putString(Constant.WEB_ID, list.get(position).getId());      //当前轮播图 id
                bundle.putString(Constant.WEB_TITLE, "图文详情");                    //设置web页面标题
                JumperUtils.JumpTo(HomeActivity.this, WebDateActivity.class, bundle);//跳转到下一页面
            }
        });
    }

    /**
     * 首页 通知公告 网络请求 返回具体 数据实体
     */
    @Subscriber(tag = Constant.BUS_HOME_NOTICE, mode = ThreadMode.MAIN)
    public void initDayList(final HomeNoticeBean bean) {
        tvHomeNotice.setText(bean.getTitle());
        //通知公告点击事件
        layoutHomeNotice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**
                 * 跳转 webView事件
                 */
                Bundle bundle = new Bundle();
                bundle.putString(Constant.WEB_METHOD, Constant.WEB_NAME_NOTICE);     //通知公告 方法名拼接字段
                bundle.putString(Constant.WEB_ID, bean.getId());                     //当前通知公告 id
                bundle.putString(Constant.WEB_TITLE, "公告详情");                     //设置web页面标题
                JumperUtils.JumpTo(HomeActivity.this, WebDateActivity.class, bundle);//跳转到下一页面
            }
        });
    }

    /**
     * 首页 校内动态 网络请求 加载是否成功
     */
    @Subscriber(tag = Constant.BUS_HOME_DYNAMIC_ON_COMPLETED, mode = ThreadMode.MAIN)
    public void initTestingOnCompleted(String str) {
        //销毁handler
        time_handler.removeCallbacks(time_runnable);
        timeDailog.dismiss();
        dialog.dismiss();
    }

    /**
     * 首页 首次请求 校内动态 网络请求 返回具体 数据实体
     */
    @Subscriber(tag = Constant.BUS_HOME_DYNAMIC_NOTICE, mode = ThreadMode.MAIN)
    public void homeDynamic(final ImageTextJsonPack pack) {
        //填充列表集合数据
        homeDynamicList.addAll(pack.getDataList());
        //填充列表数据
        dynamicAdapter = new ImageTextAdapter(HomeActivity.this, pack.getDataList());
        rvHomeDynamicList.setLayoutManager(new FullyLinearLayoutManager(HomeActivity.this, LinearLayoutManager.VERTICAL, false));
        rvHomeDynamicList.setAdapter(dynamicAdapter);
        //校内动态点击事件
        initDynamicItemClick();
    }

    /**
     * 首页 获取签到信息 网络请求 加载是否成功
     */
    @Subscriber(tag = Constant.BUS_HOME_SIGN_MSG_ON_COMPLETED, mode = ThreadMode.MAIN)
    public void initSignMsgHttpOnCompleted(String str) {
        //销毁handler
        time_handler.removeCallbacks(time_runnable);
        timeDailog.dismiss();
        dialog.dismiss();
    }

    /**
     * 首页 获取签到信息 校内动态 网络请求 返回具体 数据实体
     */
    @Subscriber(tag = Constant.BUS_HOME_SIGN_MSG, mode = ThreadMode.MAIN)
    public void initSignMsgHttp(final ScheduleWeekBean bean) {

        //设置 弹出 dialog 内容
        signMsgDialog = new HomeSignDialog(HomeActivity.this) {
            @Override
            public void setView(TextView tvSignDate, TextView tvSignContent,Button btnSign) {
                //签到状态
                String signStage = bean.getQD_State();
                //是否签到过
                String sfqd = bean.getSFQD();
                //填充标题
                tvSignDate.setText(DataUtils.getNowDate("yyyy/MM/dd")
                        +"  "+DataUtils.getNowWeek()+"  "+DataUtils.getNowDate("HH:mm"));

                //判断今天是否有签到 信息了
                if (bean.getState().equals("1")){
                    //填充内容
                    tvSignContent.setText(bean.getKCM()+" 老师："+
                            bean.getTeacherName()+" "+bean.getSKDD());
                    /**
                     * 根据 当前 签到状态，判断按钮是否可点击的样式
                     */
                    if (signStage.equals(Constant.SIGN_NO)){
                        btnSign.setText("签到");
                        btnSign.setEnabled(true);
                        btnSign.setBackgroundResource(R.drawable.public_btn_blue_selected);
                    }
                    if (signStage.equals(Constant.SIGN_YES)){
                        btnSign.setText("已签到");
                        if (sfqd.equals("1")){
                            btnSign.setText("已签到过");
                        }
                    }
                    if (signStage.equals(Constant.SIGN_LATE)){
                        if (sfqd.equals("1")){
                            btnSign.setText("已签到过（已迟到）");
                            btnSign.setEnabled(false);
                        }else{
                            btnSign.setText("签到（已迟到）");
                            btnSign.setEnabled(true);
                            btnSign.setBackgroundResource(R.drawable.public_btn_red_selected);
                        }
                    }
                }else{
                    //填充内容
                    tvSignContent.setText("今天没有课程了~");
                    //按钮
                    btnSign.setText("无需签到");
                    btnSign.setEnabled(false);
                }
            }

            @Override
            public void setSign() {
                //点击签到
                initSignHttp(bean);
            }
        };
        signMsgDialog.show();
    }

    /**
     * 首页 签到 网络请求 加载是否成功
     */
    @Subscriber(tag = Constant.BUS_HOME_SIGN_ON_COMPLETED, mode = ThreadMode.MAIN)
    public void initSignOnCompleted(String str) {
        //销毁handler
        time_handler.removeCallbacks(time_runnable);
        timeDailog.dismiss();
        dialog.dismiss();
    }

    /**
     * 首页 签到 校内动态 网络请求 返回具体 数据实体
     */
    @Subscriber(tag = Constant.BUS_HOME_SIGN, mode = ThreadMode.MAIN)
    public void initSign(InfoReturnBean bean) {
        if (bean.getState().equals("1")){
            signDialog = new MaterialDialog.Builder(HomeActivity.this)
                    .title("成功")
                    .content("您已经"+bean.getQD_state()+"了！")
                    .positiveText("确认")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {
                            signDialog.dismiss();
                        }
                    }).show();
        }else{
            signDialog = new MaterialDialog.Builder(HomeActivity.this)
                    .title("失败")
                    .content(bean.getMsg())
                    .positiveText("知道了")
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(MaterialDialog dialog, DialogAction which) {
                            signDialog.dismiss();
                        }
                    }).show();
        }
        // 设置点击屏幕Dialog不消失
        signDialog.setCanceledOnTouchOutside(false);
        //取消Back键监听
        signDialog.setCancelable(false);
    }

    /**
     * 首页 首次请求 校内动态 网络请求 上拉加载数据
     */
    @Subscriber(tag = Constant.BUS_HOME_DYNAMIC_FOOT_NOTICE)
    public void FooterAddress(ImageTextJsonPack pack) {
        final List<ImageTextBean> footList = pack.getDataList();

        //开启延时操作
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                /**
                 * 判断是否有数据
                 * 当 返回列表 数据 size 0 没有更多数据可加载了
                 */
                if (footList.size() == 0) {
                    //page 不允许 + 1
                    dynamicPageFlag = false;
                    //更改 文字 底部状态
                    dynamicAdapter.changeMoreStatus(Constant.NO_LOAD_MORE);
                } else {
                    //page 允许 + 1
                    dynamicPageFlag = true;
                    //填充上拉加载新的列表集合数据
                    homeDynamicList.addAll(footList);
                    if (dynamicAdapter != null) {
                        //加载到adapter里面
                        dynamicAdapter.addFooterItem(footList);
                    }
                    //设置回到上拉加载更多
                    dynamicAdapter.changeMoreStatus(Constant.PULLUP_LOAD_MORE);
                    ToastUtils.showShort(HomeActivity.this, "更新了 " + footList.size() + " 条目数据");
                }
                //防止 重复加载
                dynamicFlag = true;
            }
        }, 1000);
    }



    /**
     * 校内动态 上拉加载事件
     */
    private void initLoadMoreListener() {
        /***
         * 1、重要说明 这里 因为布局是 ScrollView 嵌套 RecyleView 所以 这里要 监听 ScrollView 滑动事件，
         * 2、这里 加了一个 flag 是解决上拉加载数据 执行多次，flag 标志 线程执行完毕 才能上拉
         */
        svHome.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // 判断 scrollView 当前滚动位置在顶部
                if (svHome.getScrollY() == 0) {
                }
                if (dynamicFlag && dynamicAdapter != null) {
                    // 判断scrollview 滑动到底部
                    // scrollY 的值和子view的高度一样，滑动到了底部
                    if (svHome.getChildAt(0).getHeight() - svHome.getHeight() == svHome.getScrollY()) {
                        dynamicFlag = false;
                        //设置正在加载更多
                        dynamicAdapter.changeMoreStatus(Constant.LOADING_MORE);
                        //设置 加载数据类型（上拉加载）
                        mApiManager.getType(Constant.PULLUP_LOAD_MORE);
                        //如果 为 true 可以 查看下一页
                        if (dynamicPageFlag) {
                            //数据请求
                            page = page + 1;
                        }
                        mApiManager.homeDynamic(Constant.HTTP_HOME_DYNAMIC_ACTION, page + "", rows + "");
                    }
                }
                return false;
            }
        });
    }

    /**
     * 重新 加载 本页面数据
     */
    @Override
    protected void onRestart() {
        super.onRestart();
        //刷新当前页面
        if (falg) {
            /**
             * 初始化参数
             */
            page = 1;              //当前页
            rows = 5;              //数据行数
            timeSecond = 10;
            initHttp();
            falg = false;
        }
    }

    /**
     * 屏蔽 back 键
     */
    @Override
    public void onBackPressed() {
//        super.onBackPressed();
    }
}
